var express = require('express');
var router = express.Router();
var md5 = require('md5');
var request = require('request');
var consts = require('../common/constants');

/* GET home page. */
router.get('/', function(req, res, next) {
  		res.render('login', { title: 'login' });
});
//登录
router.post('/login', function(req, res, next) {
	var params = {
        username: req.body.name,
        password: req.body.password,
    };
    var token = JSON.stringify(params)+ "|" + consts.MD5_String;
    token = md5(token);
    var url = consts.APP_HOST + '/api/auth/login?token=' + token;
    var options = {
        url: url,
        method: 'POST',
        json: true,
        body: params
    };
    console.log(params.username);
    request(options, function(err, httpResponse, body) {
    	if(body.status){
    			res.render('login', {
						title: '登录',
						error: '账号或密码错误,请重新输入',
						text: '登录'
					})
    	}
    	else{
    		res.cookie('name',params.username);
    		res.cookie('token',body.token);
    		res.redirect('/');
    	}
  	})
});
//退出
router.get('/exit', function(req, res, next) {
	    res.cookie('name',"");
    	res.cookie('token',"");
  		res.redirect('/login');
});
module.exports = router;
